// 新闻模板
const newsTemplate = `
  <div class="list">
    <img src="./images/newsPicture.png" alt="" class="newsPicture">
    <div class="information">
      <a href="#" class="news-title">首届数学与人工智能科学大会成功召开</a>
      <br>
      <span>发布人：xxx</span>
      <span>时间：2020-xx-xx</span>
      <span>阅读量：5w+</span>
      <p>首届数学与人工智能科学大会于2024年8月29日至9月1日在重庆融汇国际酒店成功召开
        本次大会由中国运筹学会数学与智用数学中心联合承办，国家次大会由中国运筹学会数</p>
    </div>
  </div>
`;

// 每页显示的新闻数量
const pageSize = 5;
// 总新闻数量
const totalNews = 400;
// 总页数
const totalPages = Math.ceil(totalNews / pageSize);

// 渲染指定页的新闻
const renderNewsPage = (pageNum) => {
  const newsList = document.querySelector('.news-list');
  // 清空现有内容（保留分页控件）
  const pagination = document.querySelector('.pagination');
  if (pagination) pagination.remove();

  // newsList.innerHTML = '';

  // 计算当前页应显示的新闻索引范围
  const startIndex = (pageNum - 1) * pageSize;
  const endIndex = Math.min(startIndex + pageSize, totalNews);

  // // 添加当前页的新闻
  // for (let i = startIndex; i < endIndex; i++) {
  //   // 克隆模板并添加到列表
  //   const tempDiv = document.createElement('div');
  //   tempDiv.innerHTML = newsTemplate;
  //   const newsItem = tempDiv.firstElementChild;
  //   // 为每条新闻添加唯一标识
  //   newsItem.classList.add(`list${i + 1}`);
  //   newsList.appendChild(newsItem);
  // }

  // 渲染分页控件
  renderPagination(totalNews, pageNum, totalPages);
};

// 渲染分页控件
const renderPagination = (total, currentPage, totalPages) => {
  const listContainer = document.querySelector('.news-list');
  if (!listContainer) return;

  const paginationDiv = document.createElement('div');
  paginationDiv.className = 'pagination';

  // 显示总记录数和当前页码信息
  paginationDiv.innerHTML = `
    <div class="pagination-info">
      <span>共 ${total} 条记录，当前第 ${currentPage} 页，共 ${totalPages} 页</span>
    </div>
  `;

  // 创建页码导航容器
  const navigationContainer = document.createElement('div');
  navigationContainer.className = 'pagination-navigation';

  // 上一页按钮
  const prevButton = document.createElement('button');
  prevButton.textContent = '上一页';
  prevButton.disabled = currentPage <= 1;
  prevButton.addEventListener('click', () => {
    if (currentPage > 1) {
      renderNewsPage(currentPage - 1);
    }
  });
  navigationContainer.appendChild(prevButton);

  // 页码按钮
  const maxVisiblePages = 5;
  let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
  let endPage = startPage + maxVisiblePages - 1;

  if (endPage > totalPages) {
    endPage = totalPages;
    startPage = Math.max(1, endPage - maxVisiblePages + 1);
  }

  // 首页按钮和前省略号
  if (startPage > 1) {
    const firstPageButton = document.createElement('button');
    firstPageButton.textContent = '1';
    firstPageButton.addEventListener('click', () => {
      renderNewsPage(1);
    });
    navigationContainer.appendChild(firstPageButton);

    if (startPage > 2) {
      const ellipsis = document.createElement('span');
      ellipsis.textContent = '...';
      navigationContainer.appendChild(ellipsis);
    }
  }

  // 中间页码按钮
  for (let i = startPage; i <= endPage; i++) {
    const pageButton = document.createElement('button');
    pageButton.textContent = i;
    if (i === currentPage) {
      pageButton.disabled = true;
      pageButton.classList.add('active');
    }
    pageButton.addEventListener('click', () => {
      renderNewsPage(i);
    });
    navigationContainer.appendChild(pageButton);
  }

  // 后省略号和尾页按钮
  if (endPage < totalPages) {
    if (endPage < totalPages - 1) {
      const ellipsis = document.createElement('span');
      ellipsis.textContent = '...';
      navigationContainer.appendChild(ellipsis);
    }

    const lastPageButton = document.createElement('button');
    lastPageButton.textContent = totalPages;
    lastPageButton.addEventListener('click', () => {
      renderNewsPage(totalPages);
    });
    navigationContainer.appendChild(lastPageButton);
  }

  // 下一页按钮
  const nextButton = document.createElement('button');
  nextButton.textContent = '下一页';
  nextButton.disabled = currentPage >= totalPages;
  nextButton.addEventListener('click', () => {
    if (currentPage < totalPages) {
      renderNewsPage(currentPage + 1);
    }
  });
  navigationContainer.appendChild(nextButton);

  // 添加页码输入框和跳转按钮
  const jumpContainer = document.createElement('div');
  jumpContainer.className = 'pagination-jump';
  jumpContainer.innerHTML = `
    <span>跳转到</span>
    <input type="number" id="page-input" min="1" max="${totalPages}" value="${currentPage}">
    <span>页</span>
    <button id="jump-button">确定</button>
  `;

  navigationContainer.appendChild(jumpContainer);
  paginationDiv.appendChild(navigationContainer);
  listContainer.appendChild(paginationDiv);

  // 跳转按钮事件
  const jumpButton = document.getElementById('jump-button');
  const pageInput = document.getElementById('page-input');

  const handleJump = () => {
    const pageNumber = parseInt(pageInput.value, 10);
    if (pageNumber >= 1 && pageNumber <= totalPages && !isNaN(pageNumber)) {
      renderNewsPage(pageNumber);
    } else {
      alert(`请输入有效的页码 (1-${totalPages})`);
      pageInput.value = currentPage;
    }
  };

  jumpButton.addEventListener('click', handleJump);

  pageInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      handleJump();
    }
  });

  // 输入框失去焦点时验证
  pageInput.addEventListener('blur', () => {
    const pageNumber = parseInt(pageInput.value, 10);
    if (isNaN(pageNumber) || pageNumber < 1 || pageNumber > totalPages) {
      pageInput.value = currentPage;
    }
  });
};

// 初始化第一页
renderNewsPage(1);